<template>
  <div>
    <el-card class="operator-button-card">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="flex">
            <h2 class="operator-button-label" style="line-height: 32px;">{{ $t("operator.channel") }}</h2>
            <el-switch
              v-if="flyDeskSwitch === '1' && isAuth('10400202.MANAGE')"
              v-model="flyDeskToggle"
              class="align-top"
              active-value="1"
              inactive-value="0"
              @change="saveFunctionHandle"
            />
          </div>
          <div>
            <el-button
              v-if="flyDeskSwitch === '1' && isAuth('10400202.MANAGE')"
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="
                () => {
                  dialogVisible = true;
                }
              "
            />
          </div></div
      ></template>
      <el-empty
        v-if="flyDeskSwitch === '0'"
        :image-size="100"
        :description="$t('operator.function_not_enabled')"
      >
        <el-button
          v-if="isAuth('10400202.MANAGE')"
          type="primary"
          size="small"
          @click="handleOpen"
          >{{ $t("operator.open") }}</el-button
        >
      </el-empty>
      <el-form v-else size="small" label-suffix=":" label-width="250px">
        <el-form-item :label="$t('operator.time_balance')">
          <span class="text-blue-1 cursor-pointer" @click="showDialog('timeBalance')">
            {{ remainTime }} {{ $t("common.time.minutes") }}
          </span>
          <span
            class="ml-8 text-xl text-blue-1 cursor-pointer"
            @click="showDialog('channelRecord')"
          >
            <svg-icon icon-class="time" />
          </span>
        </el-form-item>
        <el-form-item :label="$t('operator.chnnel_balance')">
          <span class="text-blue-1 cursor-pointer" @click="showDialog('channelBalance')">
            {{ remainChnl }} {{ $t("operator.remainingChnl") }}
          </span>
        </el-form-item>
      </el-form>
    </el-card>
    <flydesk-dialog
      v-model="dialogVisible"
      :title="$t('operator.charge')"
      :remain-time="remainTime"
      :remain-chnl="remainChnl"
      :operator-id="operatorId"
      @confirm="refresh"
    />
    <el-dialog
      :visible="historyVisible"
      :title="getName()"
      @close="historyVisible = false"
    >
      <el-card
        shadow="never"
        style="border: 0px"
        :body-style="{ padding: '0px' }"
        :page-size="historyPageSize"
        :total="historyRows"
        :current-page="historyPageNo"
        @current-change="currentHistoryChangeHandle"
      >
        <el-form class="search-box" inline size="small" @submit.prevent.native>
          <el-form-item>
            <el-input
              v-model.trim="devSn"
              :placeholder="$t('device.sn')"
              clearable
              maxlength="32"
              style="width: 200px"
              @keyup.enter.native="getFlyDeskConsumeHistory()"
              @clear="getFlyDeskConsumeHistory"
              @blur="() => (devSn = devSn.trim())"
            />
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="startTime"
              style="width: 160px"
              type="date"
              value-format="timestamp"
              :placeholder="$t('common.start_time')"
            />
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="endTime"
              style="width: 160px"
              type="date"
              value-format="timestamp"
              :placeholder="$t('common.end_time')"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="p-1.5 align-middle"
              @click="getFlyDeskConsumeHistory()"
            >
              <svg-icon icon-class="search" class="text-lg" />
            </el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="historyLoading" :data="flydeskHistoryData">
          <el-table-column prop="bindTarget" label="SN" align="center">
            <template v-slot="scope">
              {{ scope.row.bindTarget }}
            </template>
          </el-table-column>
          <el-table-column prop="startTimestamp" :label="$t('merchant.startTime')">
            <template v-slot="{ row }">
              <span>{{ dateFilter(row.startTimestamp) }}</span> &nbsp;
              <span>{{ timeFilter(row.startTimestamp) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="devSn" :label="$t('page.use_time')" align="center">
            <template v-slot="scope">
              {{
                calcUseTime(
                  scope.row.startTimestamp,
                  scope.row.lastTimestamp,
                  scope.row.finishTimestamp
                )
              }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-dialog>
    <el-dialog :visible="showChannleVisible" :title="getName()" @close="close">
      <el-card
        shadow="never"
        style="border: 0px"
        :body-style="{ padding: '0px' }"
        :page-size="pageSize"
        :total="rows"
        :current-page="pageNo"
        @current-change="currentChangeHandle"
      >
        <el-table v-loading="dataListLoading" :data="flyKeyByResData">
          <el-table-column
            prop="resEffectTime"
            :label="$t('operator.effectDate')"
            width="120px"
            align="center"
          >
            <template v-slot="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="dateFilter(scope.row.resEffectTime)"
                placement="top-start"
              >
                <div class="cursor-pointer">
                  <el-tag
                    v-if="billStatus(scope.row.resEffectTime)"
                    type="success"
                    size="small"
                    >{{ $t("operator.bill_status_active") }}</el-tag
                  >
                  <el-tag v-else type="info" size="small">{{
                    $t("operator.bill_status_unactive")
                  }}</el-tag>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <!--                    <el-table-column prop="resCapacity" :label="$t('operator.res_remain')" />-->
          <el-table-column prop="resRemain" :label="$t('operator.res_remain')">
            <template v-slot="scope">
              <div v-if="scope.row.resType === 'TIME'">
                {{
                  scope.row.resRemain +
                  "/" +
                  scope.row.resCapacity +
                  "(" +
                  $t("common.time.min") +
                  ")"
                }}
                <el-progress
                  :percentage="
                    ((scope.row.resRemain * 100) / scope.row.resCapacity).toFixed(0)
                  "
                  :show-text="false"
                />
              </div>
              <div v-else>
                {{ scope.row.resRemain }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="resEffectTime"
            :formatter="formatDate"
            :label="$t('operator.effectDate')"
          >
            <template v-slot="scope">
              <span v-if="leftDay(scope.row.resEffectTime, scope.row.resExpireTime)"
                >{{ $t("common.time.left") }}
                {{ leftDay(scope.row.resEffectTime, scope.row.resExpireTime) }}
                {{ $t("common.time.day") }}</span
              >
              <el-progress
                :percentage="
                  leftPercent(scope.row.resEffectTime, scope.row.resExpireTime)
                "
                :show-text="false"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="orderTime"
            :formatter="formatDate"
            :label="$t('operator.order_time')"
            width="120px"
          />
          <el-table-column prop="orderDesc" :label="$t('common.remark')" />
        </el-table>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import { timeFilter, dateFilter } from "@/filters/index";
import { formatDate } from "@/utils/formatDate";
import {
  addLicense,
  getFlyDeskRemainTime,
  // getFlyDeskByChannel,
  getFlyDeskByResType,
  getFlyDeskConsumeHistory,
  configure,
} from "@/api/operator";
import FlydeskDialog from "./flydesk-dialog.vue";
import { isAuth } from "@/utils";
export default {
  components: { FlydeskDialog },
  props: {
    operatorId: {
      require: true,
      type: String,
      default: null,
    },
  },
  data() {
    const licenseValidate = (rule, value, callback) => {
      console.log(value);
      if (!value) {
        return callback(new Error(this.$t("operator.licenseEmptyCheck")));
      } else {
        callback();
      }
    };
    const quantityValidate = (rule, value, callback) => {
      console.log(value);
      if (value <= 0) {
        return callback(new Error(this.$t("operator.quantityCheck")));
      } else if (value === undefined) {
        return callback(new Error(this.$t("common.nullInputTip")));
      } else {
        callback();
      }
    };
    const effectTimeValidate = (rule, value, callback) => {
      console.log(value);
      if (value <= 0) {
        return callback(new Error(this.$t("operator.effectTimeCheck")));
      } else {
        callback();
      }
    };
    return {
      flyDeskToggle: "0",
      flyDeskSwitch: "0",
      dataListLoading: false,
      showChannleVisible: false,
      activeName: "first",
      flydeskHistoryData: [],
      flyKeyByResData: [],
      bizCode: "BIZ-FLY-DESKTOP",
      remainTime: 0,
      remainChnl: 0,
      pageNo: 1,
      pageSize: 5,
      devSn: "",
      rows: 0,
      startTime: null,
      endTime: null,
      effect: 0,
      resType: "TIME",
      historyPageNo: 1,
      historyPageSize: 5,
      historyRows: 0,
      historyLoading: false,
      historyVisible: false,
      dialogVisible: false,
      form: {
        radio: {},
        quantity: 1,
        effectTimestamp: "",
        remark: "",
      },
      rules: {
        license: [{ required: true, validator: licenseValidate, trigger: "change" }],
        quantity: [{ required: true, validator: quantityValidate, trigger: "change" }],
        effectTimestamp: [
          { required: true, validator: effectTimeValidate, trigger: "change" },
        ],
        radio: [{ required: true, validator: licenseValidate, trigger: "change" }],
      },
    };
  },
  created() {
    this.flyDeskRemainTime();
    // this.getLicenses();
  },
  methods: {
    timeFilter,
    dateFilter,
    handleOpen() {
      this.flyDeskToggle = "1";
      this.saveFunctionHandle();
    },
    saveFunctionHandle() {
      this.$confirm(this.$t("operator.save_cfg"), this.$t("page.tip"), {
        confirmButtonText: this.$t("page.confirm"),
        cancelButtonText: this.$t("page.cancel"),
        type: "warning",
      })
        .then(() => {
          configure(this.operatorId, { flyDeskSwitch: this.flyDeskToggle })
            .then((res) => {
              this.$message.success(this.$t("common.success"));
              this.flyDeskSwitch = this.flyDeskToggle;
            })
            .catch((err) => {
              this.$confirmError(err);
              this.flyDeskToggle = this.flyDeskToggle === "1" ? "0" : "1";
            });
        })
        .catch((e) => {
          this.flyDeskToggle = this.flyDeskToggle === "1" ? "0" : "1";
        });
    },
    leftDay(startTime, endTime) {
      if (startTime > new Date().getTime() / 1000) {
        return ((endTime - startTime) / 86400).toFixed(0);
      } else if (endTime < new Date().getTime() / 1000) {
        return 0;
      } else {
        return ((endTime - new Date().getTime() / 1000) / 86400).toFixed(0);
      }
    },
    leftPercent(startTime, endTime) {
      if (startTime > new Date().getTime() / 1000) {
        return 100;
      } else if (endTime < new Date().getTime() / 1000) {
        return 0;
      } else {
        return ((endTime - new Date().getTime() / 1000) / (endTime - startTime)) * 100;
      }
    },
    calcUseTime(start, last, finish) {
      if (finish) {
        return ((finish - start) / 60).toFixed(1);
      } else {
        return ((last - start) / 60).toFixed(1);
      }
    },
    close() {
      this.devSn = "";
      this.showChannleVisible = false;
    },
    billStatus(startTime) {
      return startTime < new Date().getTime() / 1000;
    },
    refresh() {
      this.flyDeskRemainTime();
    },
    formatDate(row, column, cellValue, index) {
      return formatDate(cellValue, "YYYY-MM-DD");
    },
    flyDeskRemainTime() {
      getFlyDeskRemainTime(this.operatorId, { currentlyEffect: -1 })
        .then((res) => {
          this.remainTime = res.time;
          this.remainChnl = res.channel;
          this.flyDeskSwitch = res.flyDeskSwitch;
          this.flyDeskToggle = res.flyDeskSwitch;
        })
        .catch((err) => {
          this.$confirmError(err);
        });
    },
    getName() {
      if (this.resType === "TIME" && this.effect === 0) {
        return this.$t("operator.time_balance");
      } else if (this.resType === "CHNL" && this.effect === 0) {
        return this.$t("operator.chnnel_balance");
      } else if (this.resType === "TIME" && this.effect === 1) {
        return this.$t("operator.time_record");
      } else if (this.resType === "CHNL" && this.effect === 1) {
        return this.$t("operator.time_record");
        // return this.$t('operator.chnnel_record')
      }
    },
    currentChangeHandle(val) {
      this.pageNo = val;
      this.flyDeskByResTypeData();
    },
    currentHistoryChangeHandle(val) {
      this.historyPageNo = val;
      this.getFlyDeskConsumeHistory();
    },
    flyDeskByResTypeData() {
      //       分页查询加了一个参数： currentlyEffect -生效标识
      // -1：查询当前生效余额（）
      // 0：查询未过期余额
      // 1：查询所有余额，包含过期、当前生效、未生效
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        currentlyEffect: this.effect,
      };
      this.dataListLoading = true;
      getFlyDeskByResType(this.resType, this.operatorId, params)
        .then((res) => {
          this.flyKeyByResData = res.data;
          this.dataListLoading = false;

          this.rows = res.rows;
        })
        .catch((e) => {
          this.dataListLoading = false;
          this.$confirmError(e);
        });
    },
    getFlyDeskConsumeHistory() {
      const params = {
        pageNo: this.historyPageNo,
        pageSize: this.historyPageSize,
        resType: this.resType,
      };
      if (this.devSn) {
        params.devSn = this.devSn;
      }
      if (this.startTime) {
        params.startTime = this.startTime / 1000;
      }
      if (this.endTime) {
        params.endTime = this.endTime / 1000;
      }
      this.historyLoading = true;
      getFlyDeskConsumeHistory(this.operatorId, params)
        .then((res) => {
          this.flydeskHistoryData = res.data;
          this.historyRows = res.rows;
          this.historyLoading = false;
        })
        .catch((e) => {
          this.flydeskHistoryData = [];
          this.$confirmError(e);
          this.historyLoading = false;
        });
    },
    handleClick(tab, event) {
      this.pageNo = 1;
      this.flyDeskByResTypeData();
    },
    showDialog(type) {
      if (type === "timeBalance") {
        this.pageNo = 1;
        this.resType = "TIME";
        this.effect = 0;
        this.flyKeyByResData = [];
        this.showChannleVisible = true;

        this.flyDeskByResTypeData();
      } else if (type === "channelBalance") {
        this.pageNo = 1;
        this.resType = "CHNL";
        this.effect = 0;
        this.showChannleVisible = true;
        this.flyKeyByResData = [];
        this.flyDeskByResTypeData();
      } else if (type === "timeRecord") {
        this.pageNo = 1;
        this.resType = "TIME";
        this.effect = 1;
        this.historyVisible = true;
        this.flydeskHistoryData = [];

        this.getFlyDeskConsumeHistory();
      } else if (type === "channelRecord") {
        this.pageNo = 1;
        this.resType = "CHNL";
        this.effect = 1;
        this.historyVisible = true;
        this.flydeskHistoryData = [];
        this.getFlyDeskConsumeHistory();
      }
    },
    isAuth,
  },
};
</script>


<style lang="scss" scoped>
::v-deep .el-dialog .el-dialog__body {
  padding: 0;
}

</style>
